﻿using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using IndustrialSmokeCalc.SmokeCalcWCF;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.PhoneTextBox;
using System.Security.Cryptography;

namespace IndustrialSmokeCalc
{
    public partial class Login : PhoneApplicationPage
    {
        private bool isLoginValid = false;
        private bool isEmailValid = false;
        private bool isPasswordValid = false;
        private bool isConfirmPasswordValid = false;
        private bool isOfficeValid = false;
        private bool isOfficeAddressValid = false;

        private const string MatchEmailPattern = @"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b";

        public Login()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            CheckLoginStatus();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (txtUser.Text.IsEmpty())
            {
                txtUser.ChangeValidationState(ValidationState.Invalid, "Harus terisi!");
                isLoginValid = false;
            }
            else
            {
                txtUser.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                isLoginValid = true;
            }

            if (txtPass.Password.IsEmpty())
            {
                txtPass.ChangeValidationState(ValidationState.Invalid, "Harus terisi!");
                isLoginValid = false;
            }
            else
            {
                txtPass.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                isLoginValid = true;
            }
            
            if(isLoginValid)
            {
                CallLoginCheck();
            }
        }

        private void CallLoginCheck()
        {
            SmokeCalcClient sc = new SmokeCalcClient();
            sc.LoginCheckCompleted += LoginCheckCompleted;
            sc.LoginCheckAsync(txtUser.Text, GetHashCode(txtPass.Password));
        }

        private void LoginCheckCompleted(object sender, LoginCheckCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Tidak dapat melakukan koneksi ke server.\r\nCoba periksa koneksi internet anda.");
            }
            if (e.Result == "sukses")
            {
                SaveCredential();
            }
            else MessageBox.Show("Maaf, username atau password anda salah.");
        }

        private void SaveCredential()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            settings.Add("UserId", txtUser.Text);
            DataSingleton.Instance.UserId = txtUser.Text;
            settings.Save();
            NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
        }

        private void CheckLoginStatus()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains("UserId"))
            {
                DataSingleton.Instance.UserId = settings["UserId"].ToString();
                NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
            }
        }

        private void btnSignUp_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                CallRegister();
            }
        }

        private void CallRegister()
        {
            SmokeCalcClient sc = new SmokeCalcClient();
            sc.RegistrationCompleted += RegistrationCompleted;
            sc.RegistrationAsync(txtNewUser.Text, txtOffice.Text, txtOfficeAddress.Text, GetHashCode(txtNewPassword.Password));
        }

        private void RegistrationCompleted(object sender, RegistrationCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Tidak dapat melakukan koneksi ke server.\r\nCoba periksa koneksi internet anda.");
            }
            if (e.Result == "sukses")
            {
                MessageBox.Show("Registrasi sukses, silahkan login.");
                Pivot.SelectedIndex = 0;
            }
            else MessageBox.Show("Registrasi gagal, email sudah terdaftar.");
        }

        private bool Validate()
        {
            ValidateEmail();
            ValidatePassword();
            ValidateOffice();
            return isEmailValid && isPasswordValid && isConfirmPasswordValid && isOfficeValid && isOfficeAddressValid;
        }

        private void ValidateEmail()
        {
            if (txtNewUser.Text.IsEmpty())
            {
                txtNewUser.ChangeValidationState(ValidationState.Invalid, "Harus terisi!");
            }
            else
            {
                txtNewUser.ChangeValidationState(ValidationState.NotValidated, string.Empty);

                if (!Regex.IsMatch(txtNewUser.Text, MatchEmailPattern))
                {
                    txtNewUser.ChangeValidationState(ValidationState.Invalid, "Format tidak sesuai!");
                }
                else
                {
                    txtNewUser.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                    isEmailValid = true;
                }
            }
        }

        private void ValidatePassword()
        {
            if (txtNewPassword.Password.Length < 8)
            {
                txtNewPassword.ChangeValidationState(ValidationState.Invalid,
                    "Minimal 8 karakter!");
            }
            else
            {
                txtNewPassword.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                isPasswordValid = true;
            }

            if (txtConfirmPassword.Password.IsEmpty() || txtConfirmPassword.Password != txtNewPassword.Password)
            {
                txtConfirmPassword.ChangeValidationState(ValidationState.Invalid, "Password tidak cocok!");
            }
            else
            {
                txtConfirmPassword.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                isConfirmPasswordValid = true;
            }
        }

        private void ValidateOffice()
        {
            if (txtOffice.Text.IsEmpty())
            {
                txtOffice.ChangeValidationState(ValidationState.Invalid, "Harus terisi!");
            }
            else
            {
                txtOffice.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                isOfficeValid = true;
            }

            if (txtOfficeAddress.Text.IsEmpty())
            {
                txtOfficeAddress.ChangeValidationState(ValidationState.Invalid, "Harus terisi!");
            }
            else
            {
                txtOfficeAddress.ChangeValidationState(ValidationState.NotValidated, string.Empty);
                isOfficeAddressValid = true;
            }
        }

        public static string GetHashCode(string input)
        {
            var sha256 = new SHA256Managed();
            return Convert.ToBase64String(sha256.ComputeHash(new System.Text.UTF8Encoding().GetBytes(input)));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            while (NavigationService.BackStack.Any())
            {
                NavigationService.RemoveBackEntry();
            }
        }
    }
}